package com.miao.test.support;

import cn.hutool.core.collection.ConcurrentHashSet;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/5/17 16:44
 * @Description:
 */
@Slf4j
public class MetricsManager {

    private static final List<SocketMetrics> metrics = new CopyOnWriteArrayList<>();

    public static void addMetrics(SocketMetrics socketMetrics) {
        metrics.add(socketMetrics);
    }

    public static void clear() {
        metrics.clear();
    }

    public static MetricsStatistics statistics() {
        if (metrics.isEmpty()) {
            return new MetricsStatistics();
        }
        List<SocketMetrics> filterList = metrics.stream().filter(SocketMetrics::success).collect(Collectors.toList());
        long[] longs = metrics.stream().mapToLong(SocketMetrics::getRespTime).toArray();
        log.info("数组:{}", JSON.toJSONString(longs));
        int requestNum = filterList.size();
        long beginTime = filterList.stream().mapToLong(SocketMetrics::getRequestStamp).min().orElse(0);
        long endTime = filterList.stream().mapToLong(SocketMetrics::getRespStamp).max().orElse(0);
        long minRt = filterList.stream().mapToLong(SocketMetrics::getRespTime).min().orElse(0);
        long maxRt = filterList.stream().mapToLong(SocketMetrics::getRespTime).max().orElse(0);
        long totalRespTime = filterList.stream().mapToLong(SocketMetrics::getRespTime).sum();

        double avgRt = NumberUtil.div(totalRespTime, requestNum);
        MetricsStatistics statistics = new MetricsStatistics();
        statistics.setBeginTimestamp(beginTime);
        statistics.setEndTimestamp(endTime);
        statistics.setRequestNum(requestNum);
        statistics.setRequestNum(requestNum);
        statistics.setMaxRt(maxRt);
        statistics.setMinRt(minRt);
        statistics.setAvgRt(avgRt);
        return statistics;
    }
}
